// Z80 MCU I/O interface
// bitrowz 2025/10/25
#pragma once
#include <stdint.h>
#include <stdbool.h>

// CPLD Register Address
#define IOBASE                  (0x60000000)
#define REG_DATA                (IOBASE)
#define REG_RESET               (IOBASE + 4)
#define REG_WAIT                (IOBASE + 8)
#define REG_BUSREQ              (IOBASE + 12)
#define REG_SRAM                (IOBASE + 16)
#define REG_SPI0_DATA           (IOBASE + 20)
#define REG_SPI0_CLK_DIV        (IOBASE + 24)

// Z80 I/O event type
typedef enum {
    IO_READ = 0,        // Z80 reads data from MCU
    IO_WRITE            // Z80 writes data to MCU
} IOEvent;

// Z80 I/O request descriptor
typedef struct {
    IOEvent  event;     // Event type
    uint8_t  addr;      // Peripheral address
    uint8_t* rdata;     // Pointer to data from MCU to Z80
    uint8_t* wdata;     // Pointer to data from Z80 to MCU
} PollFd;


// Initialize Z80 interface
// Must be called before any Z80 communication
void Z80_Init();

// Poll for Z80 read/write event
// fd: pointer to PollFd structure to receive event data
// Returns true if an event is available, false otherwise
bool Z80_Poll(PollFd* fd);

// Indicate that the Z80 I/O operation is complete
// Should be called after processing the I/O event
void Z80_Finish();

// Handle Z80 I/O interrupt (IORQ)
// Internal function for ISR, typically not called directly
void __Z80_IRQ();